package com.eclink.asset.setup.controller;

import cn.hutool.core.bean.BeanUtil;
import com.eclink.asset.setup.convert.OrganizationConvert;
import com.eclink.asset.setup.domain.dao.Company;
import com.eclink.asset.setup.domain.dto.CompanyDTO;
import com.eclink.asset.setup.domain.dto.OrganizationTreeNodeDTO;
import com.eclink.asset.setup.service.CompanyService;
import com.eclink.asset.setup.service.DeptService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 仓库Controller
 * 
 * @author zcc
 * @date 2022-08-05
 */
@Api("组织结构接口")
@RestController
@RequestMapping("/organization")
public class OrganizationController extends BaseController {

    @Resource
    private CompanyService service;

    @Resource
    private DeptService deptService;


    @ApiOperation("查询")
    @GetMapping("/getOrganizationTree")
    public ResponseEntity<List<OrganizationTreeNodeDTO>> getOrganizationTree() {
        List<Company> list = service.selectListAll();
        List<OrganizationTreeNodeDTO> treeNodes = BeanUtil.copyToList(list, OrganizationTreeNodeDTO.class);
        for(OrganizationTreeNodeDTO dto : treeNodes) {
            String companyId = dto.getId();
            List<SysDept> deptList = deptService.selectDeptListByCompanyId(Long.parseLong(dto.getId()));
            List<OrganizationTreeNodeDTO> children = new ArrayList<>();
            for(SysDept dept : deptList) {
                OrganizationTreeNodeDTO dtoChild = new OrganizationTreeNodeDTO();
                dtoChild.setId(companyId+'-'+dept.getDeptId());
                dtoChild.setName(dept.getDeptName());
                children.add(dtoChild);
            }
            dto.setChildren(children);
        }
        return ResponseEntity.ok(treeNodes);
    }

    @ApiOperation("查询所有")
    @GetMapping("/listAll")
    public ResponseEntity<List<Company>> listAll() {
        List<Company> list = service.selectListAll();
        return ResponseEntity.ok(list);
    }

    @ApiOperation("获取详细信息")
    @PreAuthorize("@ss.hasPermi('wms:warehouse:query')")
    @GetMapping(value = "/{id}")
    public ResponseEntity<Company> getInfo(@PathVariable("id") Long id) {
        return ResponseEntity.ok(service.selectById(id));
    }

}
